package com.jnu.testdrivendevelopment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.jnu.testdrivendevelopment.data.Book;
import com.jnu.testdrivendevelopment.data.DataBank;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BookFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BookFragment extends Fragment {
    public static final int RESULT_CODE_ADD_DATA = 996;
    public static final int REQUEST_CODE_ADD = 123;
    public static final int REQUEST_CODE_EDIT = REQUEST_CODE_ADD+1;
    private List<Book> books=new ArrayList<>();
    private MyRecyclerViewAdapter myRecylerViewAdapter;
    private DataBank dataBank;

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode== REQUEST_CODE_ADD){
            if(resultCode== RESULT_CODE_ADD_DATA){
                String text=data.getStringExtra("book_name");
                int position=data.getIntExtra("position",books.size());
                books.add(position,new Book(text,R.drawable.book_2));
                dataBank.saveData();
                myRecylerViewAdapter.notifyItemInserted(position);
                Toast.makeText(BookFragment.this.getContext(),"已添加",Toast.LENGTH_LONG).show();
            }
        }
        if(requestCode==REQUEST_CODE_EDIT){
            if(resultCode==RESULT_CODE_ADD_DATA){
                String text=data.getStringExtra("book_name");
                int position=data.getIntExtra("position",books.size());
                books.get(position).setBook_name(text);
                dataBank.saveData();
                myRecylerViewAdapter.notifyItemChanged(position);
                Toast.makeText(BookFragment.this.getContext(),"已修改",Toast.LENGTH_LONG).show();
            }
        }
    }

    public void initData(){
        dataBank = new DataBank(BookFragment.this.getContext());
        books= dataBank.loadData();
    }
    public BookFragment() {
        // Required empty public constructor
    }
    public static BookFragment newInstance() {
        BookFragment fragment = new BookFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
        initData();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView=inflater.inflate(R.layout.fragment_book,container,false);

        RecyclerView mainRecyclerView=rootView.findViewById(R.id.recycle_view_books);
        LinearLayoutManager layoutManager=new LinearLayoutManager(BookFragment.this.getContext());
        mainRecyclerView.setLayoutManager(layoutManager);
        myRecylerViewAdapter = new MyRecyclerViewAdapter(books);
        mainRecyclerView.setAdapter(myRecylerViewAdapter);
        registerForContextMenu(mainRecyclerView);

        FloatingActionButton floatingActionButton=rootView.findViewById(R.id.floatingActionButton);
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(BookFragment.this.getContext(),EditBookActivity.class);
                intent.putExtra("position",books.size());
                BookFragment.this.startActivityForResult(intent, REQUEST_CODE_ADD);
            }
        });
        // Inflate the layout for this fragment
        return rootView;
    }
    private class MyRecyclerViewAdapter extends RecyclerView.Adapter {
        private List<Book> books;

        public MyRecyclerViewAdapter(List<Book> books) {
            this.books=books;
        }

        @Override
        public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
            super.onViewAttachedToWindow(holder);
            ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
            if (lp != null && lp instanceof StaggeredGridLayoutManager.LayoutParams) {
                StaggeredGridLayoutManager.LayoutParams p = (StaggeredGridLayoutManager.LayoutParams) lp;
                p.setFullSpan(holder.getLayoutPosition() == RESULT_CODE_ADD_DATA);
            }
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_books_layout, parent, false);
            return new MyRecyclerViewAdapter.MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder Holder, int position) {
            MyRecyclerViewAdapter.MyViewHolder holder=(MyRecyclerViewAdapter.MyViewHolder) Holder;
            holder.getImageView().setImageResource(books.get(position).getBook_id());
            holder.getTextView().setText(books.get(position).getBook_name());
        }

        @Override
        public int getItemCount() {
            return books.size();
        }

        private class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
            public static final int CONTEXT_MENU_ID_ADD=1;
            public static final int CONTEXT_MENU_ID_EDIT = 2;
            public static final int CONTEXT_MENU_ID_DELETE = 3;
            private ImageView imageView;
            private TextView textView;
            int position;
            public MyViewHolder(View itemView) {
                super(itemView);
                this.textView=(TextView) itemView.findViewById(R.id.text_view_book_title);
                this.imageView=(ImageView) itemView.findViewById(R.id.image_view_book_cover);
                itemView.setOnCreateContextMenuListener(this);
            }

            public ImageView getImageView() {
                return imageView;
            }

            public TextView getTextView() {
                return textView;
            }

            @Override
            public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
                MenuItem add=contextMenu.add(Menu.NONE,CONTEXT_MENU_ID_ADD,CONTEXT_MENU_ID_ADD,"Add");
                MenuItem edit=contextMenu.add(Menu.NONE,CONTEXT_MENU_ID_EDIT,CONTEXT_MENU_ID_EDIT,"Edit");
                MenuItem delete=contextMenu.add(Menu.NONE,CONTEXT_MENU_ID_DELETE,CONTEXT_MENU_ID_DELETE,"Delete"+getAdapterPosition());

                add.setOnMenuItemClickListener(this);
                edit.setOnMenuItemClickListener(this);
                delete.setOnMenuItemClickListener(this);
            }

            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                position=getAdapterPosition();
                Intent intent=new Intent(BookFragment.this.getContext(),EditBookActivity.class);
                View dialogue_View=LayoutInflater.from(BookFragment.this.getContext()).inflate(R.layout.dialogue_input_item,null);
                AlertDialog.Builder alertDialog_Builder=new AlertDialog.Builder(BookFragment.this.getContext());
                alertDialog_Builder.setView(dialogue_View);

                EditText editName=dialogue_View.findViewById(R.id.edit_book_name);
                switch (menuItem.getItemId()){
                    case CONTEXT_MENU_ID_ADD:
                        intent.putExtra("position",position);
                        BookFragment.this.startActivityForResult(intent, REQUEST_CODE_ADD);
                        break;
                    case CONTEXT_MENU_ID_EDIT:
                        intent.putExtra("position",position);
                        intent.putExtra("book_name",books.get(position).getBook_name());
                        BookFragment.this.startActivityForResult(intent,REQUEST_CODE_EDIT);
                        break;
                    case CONTEXT_MENU_ID_DELETE:
                        tipDialog();
                        break;
                }
                return false;
            }
            private void tipDialog() {
                AlertDialog.Builder builder = new AlertDialog.Builder(BookFragment.this.getContext());
                builder.setTitle("提示：");
                builder.setMessage("是否删除数据？");
                builder.setIcon(R.mipmap.ic_launcher);
                builder.setCancelable(true);            //点击对话框以外的区域是否让对话框消失

                //设置确定按钮
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        books.remove(position);
                        dataBank.saveData();
                        Toast.makeText(BookFragment.this.getContext(),"已删除",Toast.LENGTH_LONG).show();
                        MyRecyclerViewAdapter.this.notifyItemRemoved(position);
                        dialog.dismiss();
                    }
                });
                //设置取消按钮
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(BookFragment.this.getContext(), "已取消", Toast.LENGTH_LONG).show();
                        dialog.dismiss();
                    }
                });
                AlertDialog dialog = builder.create();
                dialog.show();
            }
        }
    }

}